//
//  XHZMainController.swift
//  Weibo
//
//  Created by 许惠占 on 2017/6/27.
//  Copyright © 2017年 许惠占. All rights reserved.
//

import UIKit

/// 主控制器
class XHZMainController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        setupComposeButton()
    }
    
    /**
      portrait: 竖屏
      landscape: 横屏
     
     - 使用代码控制设备的方向，好处，可以在需要横屏的时候，单独处理！
     - 设置支持的方向之后，当前的控制器及子控制器都会遵守这个方向!
     
     注意：Swift3.0 中设置去掉了之前版本中 旋转方向的方法，采用下面的方式
     */
//    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
//        return .portrait
//    }
    
    private var _orientations = UIInterfaceOrientationMask.portrait
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        get {
            return self._orientations
        }
        set {
            self._orientations = newValue
        }
    }
    
    
    // MARK: - 私有控件
    /// 撰写按钮
    lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    // MARK: - 监听方法
    /// 撰写微博
    // FIXME：没有实现
    @objc fileprivate func composeStatus() {
        print("撰写微博")
        
        // 测试方向旋转
        let vc = UIViewController()
        
        vc.view.backgroundColor = UIColor.cz_random()
        
        let nav = UINavigationController(rootViewController: vc)
        
        present(nav, animated: true, completion: nil)
    }


}

// extension 类似于 OC 中的分类，在Swift中还可以用来切分代码块
// 可以把相近功能的函数，放在一个extension中
// 便于代码维护
// 注意：和OC的分类一样，extension中不能定义属性
// MARK: - 设置界面
extension XHZMainController {
    
    // 设置撰写按钮
    func setupComposeButton() {
        tabBar.addSubview(composeButton)
        
        // 计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count - 1
        
        // CGRectInset 正数向内缩进，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        print("撰写按钮宽度 \(composeButton.bounds.width)")
        
        // 按钮监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    //  设置所有子控制器
    func setupChildControllers() {
        
        // 从bundle 加载配置的 json
        // 1.路径 2.加载 NSData 3.反序列化转换成数组
        guard let path = Bundle.main.path(forResource: "main.json", ofType: nil), let data = NSData(contentsOfFile: path), let array = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String: AnyObject]] else {
            return
        }
        
        
//        // 在现在的很多引用程序中，界面的创建都依赖网络的 json
//        let array: [[String: AnyObject]] = [
//            ["clsName": "XHZHomeViewController" as AnyObject, "title": "首页" as AnyObject, "imageName": "home" as AnyObject, "visitorInfo": ["imageName": "", "message": "关注一些人，回这里看看有什么惊喜"] as AnyObject],
//            ["clsName": "XHZMessageViewController" as AnyObject, "title": "消息" as AnyObject, "imageName": "message_center" as AnyObject, "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"] as AnyObject],
//            ["clsName": "UIViewController" as AnyObject],
//            ["clsName": "XHZDiscoverViewController" as AnyObject, "title": "发现" as AnyObject, "imageName": "discover" as AnyObject, "visitorInfo": ["imageName": "visitordiscover_image_message", "message": "登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"] as AnyObject],
//            ["clsName": "XHZProfileViewController" as AnyObject, "title": "我" as AnyObject, "imageName": "profile" as AnyObject, "visitorInfo": ["imageName": "visitordiscover_image_profile", "message": "登录后，你的微博、相册、个人资料会显示在这里，展示给别人"] as AnyObject]
//        ]
//        
//        // 写入沙盒 - 测试数据格式是否正确
//        //(array as NSArray).write(toFile: "/Users/xuhuizhan/Desktop/demo.plist", atomically: true)
//        // 数组 -> json 序列化
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (data as NSData).write(toFile: "/Users/xuhuizhan/Desktop/demo.json", atomically: true)
        
        // 遍历数组，循环创建控制器数组
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        
        // 设置 tabBar 的子控制器
        viewControllers = arrayM
    }
    
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dict: 信息字典[clsName, title, imageName]
    /// - Returns: 子控制器
    private func controller(dict: [String: AnyObject]) -> UIViewController {
        
        // 1.取得字典内容
        guard let clsName = dict["clsName"], let title = dict["title"], let imageName = dict["imageName"], let cls = NSClassFromString(Bundle.main.namespace + "." + (clsName as! String)) as? XHZBaseViewController.Type, let visitorDict = dict["visitorInfo"] as? [String: String] else {
            return UIViewController()
        }
        
        // 2.创建视图控制器
        let vc = cls.init()
        
        vc.title = title as! String
        
        // 设置控制器的访客信息字典
        vc.visitorInfo = visitorDict
        
        // 3.设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + (imageName as! String))
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + (imageName as! String) + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        // 4.设置 tabbar 的标题字体（大小）
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .highlighted)
        // 系统默认是12字号，修改字体大小，要设置normal的字体大小
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: .normal)
        
        // 实例化导航栏控制器的时候，会调用 push 方法将 rootVC压栈
        let nav = XHZNavigationController(rootViewController: vc)
        
        return nav
    }
    
}
